<template>
  <div class="ebook-bookmark" ref="bookmark">
    <div class="ebook-bookmark-text-wrapper">
      <div class="ebook-bookmark-down-wrapper" ref="iconDown">
        <span class="icon-down"></span>
      </div>
      <div class="ebook-bookmark-text">{{text}}</div>
    </div>
    <!-- :style="isFixed ? fixedStyle : {}"是否可以定位 -->
    <div class="ebook-bookmark-icon-wrapper" :style="isFixed ? fixedStyle : {}">
      <Bookmark :color="color" :width="38" :height="80"></Bookmark>
    </div>
  </div>
</template>

<script>
  import Bookmark from '../common/Bookmark'
  import { realPx } from '@/utils/utils'
  import { ebookMixin } from '../../utils/mixin'
  import { saveBookmark, getBookmark } from '../../utils/localStorage'
  import { addMark, deleteMark } from '../../api/store'
  const BLUE = '#346cbc'
  const WHITE = '#fff'
  export default {
    mixins: [ebookMixin],
    components: {
      Bookmark
    },
    data() {
      return {
        text: '',
        color: WHITE,
        isFixed: false, // 书签是否可以定位，添加书签定位在页面上
        id: 0 // 返回的书签Id
      }
    },
    computed: {
      // 书签高度
      height() {
        return realPx(45) // 35
      },
      // 临界值
      threshold() {
        return realPx(65) // 55
      },
      // 定位样式
      fixedStyle() {
        return {
          position: 'fixed',
          right: `${(window.innerWidth - this.$refs.bookmark.clientWidth) / 2}px`,
          top: 0
        }
      }
    },
    watch: {
      offsetY(v) {
        // console.log(v)
        if (!this.bookAvailable || this.menuVisible || this.settingVisible >= 0) {
          return
        }
        // 状态2：刚刚吸顶阶段，未到达临界状态
        if (v >= this.height && v < this.threshold) {
          // console.log('到达第二阶段')
          this.beforeThreshold(v)
        } else if (v >= this.threshold) {
          // 状态3到达临界状态，那组可添加状态
          // console.log('到达第三阶段')
          this.afterThreshold(v)
        } else if (v > 0 && v < this.height) {
          // 状态1：正常状态，未超过书签的高度
          // console.log('到达第一阶段')
          this.beforeHeight()
        } else if (v === 0) {
          // 状态4：归位的状态
          // console.log('到达第四阶段')
          this.restore()
        }
      },
      // 监听是否位书签
      isBookmark(isBookmark) {
        this.isFixed = isBookmark
        if (isBookmark) {
          this.color = BLUE
        } else {
          this.color = WHITE
        }
      }
    },
    methods: {
      // 增加书签到页面上，一本书的书签列表在localStorage中
      addBookmark() {
        // 这个数组存了我们所有的书签
        this.bookmark = getBookmark(this.fileName)
        if (!this.bookmark) {
          this.bookmark = []
        }
        // currentLocation当前页的信息，包括start.cfi和end.cfi
        const currentLocation = this.currentBook.rendition.currentLocation()
        // console.log(this.currentBook)
        console.log(currentLocation)
        // 当前书签的章节
        const currentSector = currentLocation.start.href
        // console.log(currentSector)
        // 通过正则表达式获取cfi感叹号前面的内容
        // 找到感叹号前面的内容
        const cfibase = currentLocation.start.cfi.replace(/!.*/, '')
        // 获取感叹号后面的内容
        const cfistart = currentLocation.start.cfi.replace(/.*!/, '').replace(/\)$/, '')
        // console.log(cfibase, cfistart)
        // 获取感叹号后面的内容
        const cfiend = currentLocation.end.cfi.replace(/.*!/, '').replace(/\)$/, '')
        // console.log(cfibase, cfistart, cfiend)
        // cfi的信息拼接成字符串cfirange
        const cfirange = `${cfibase}!,${cfistart},${cfiend})`
        // console.log(cfirange)
        // 通过getRange()方法获取range对象
        this.currentBook.getRange(cfirange).then(range => {
          // console.log(range.toString())
          // 查找两个空格这样的情况，range对象的toString()可以获取文本内容,g全局查找,\s空格
          let text = range.toString().replace(/\s\s/g, '')
          // console.log(text)
          const cfi = currentLocation.start.cfi
          // const metadata = this.book.loaded.metadata
          const name = this.fileName.split('/')[1]
          console.log('name:', name)
          // console.log(this.fileName)
          console.log('currentSector:', currentSector)
          console.log('cfi:', cfi)
          console.log('text:', text)
          // API增加书签到数据库
          addMark(name, currentSector, cfi, text).then(response => {
            console.log(response)
            this.id = response.m_id
            console.log(this.id)
          })
          // 将text连接上书签id，将他一起存到localstorage中
          text = range.toString().replace(/\s\s/g, '') + '!' + this.id
          this.bookmark.push({
            cfi: currentLocation.start.cfi,
            text: text
          })
          saveBookmark(this.fileName, this.bookmark)
        })
      },
      // 删除页面上书签
      removeBookmark() {
        const currentLocation = this.currentBook.rendition.currentLocation()
        const cfi = currentLocation.start.cfi
        this.bookmark = getBookmark(this.fileName)
        if (this.bookmark) {
          saveBookmark(this.fileName, this.bookmark = this.bookmark.filter(item =>
          item.cfi !== cfi))
        }
        // const id = parseInt(this.bookmark.text.replace(/.*!/, ''))
        // API从数据库中删除书签
        console.log('this.fileName', this.fileName)
        console.log('id', this.id)
        const name = this.fileName.split('/')[1]
        deleteMark(name, this.id).then(res => {
          console.log('删除书签返回', res)
        })
        this.setIsBookmark(false)
      },
      // 状态4：归位封装
      restore() {
        // 有一个过度动画
        setTimeout(() => {
          this.$refs.bookmark.style.top = `${-this.height}px`
          this.$refs.iconDown.style.transform = 'rotate(0deg)'
        }, 200)
        // 设置当前页是否位书签页
        if (this.isFixed) {
          this.setIsBookmark(true)
          // 添加书签
          this.addBookmark()
        } else {
          this.setIsBookmark(false)
          // 删除书签
          this.removeBookmark()
        }
      },
      // 状态1封装
      beforeHeight() {
       if (this.isBookmark) {
         this.text = this.$t('book.pulldownDeleteMark')
         this.color = BLUE
         this.isFixed = true
       } else {
         this.text = this.$t('book.pulldownAddMark')
         this.color = WHITE
         this.isFixed = false
       }
      },
      // 状态2封装,吸顶效果
      beforeThreshold(v) {
        // console.log('到达第二阶段')
          // bookmark的top值与offsetY保持一致，相对位移
          this.$refs.bookmark.style.top = `${-v}px`
          // 调用状态1
          this.beforeHeight()
          const iconDown = this.$refs.iconDown
          if (iconDown.style.transform === 'rotate(180deg)') {
            iconDown.style.transform = 'rotate(0deg)'
          }
      },
      // 状态3封装
      afterThreshold(v) {
        // 状态3：超越临界状态
          // console.log('到达第三阶段')
          this.$refs.bookmark.style.top = `${-v}px`
          if (this.isBookmark) {
            this.text = this.$t('book.releaseDeleteMark')
            this.color = WHITE
            this.isFixed = false
          } else {
            this.text = this.$t('book.releaseAddMark')
            this.color = BLUE
            this.isFixed = true
          }
          // 图标旋转
          const iconDown = this.$refs.iconDown
          if (iconDown.style.transform === 'rotate(0deg)' ||
            iconDown.style.transform === '') {
            iconDown.style.transform = 'rotate(180deg)'
          }
      }
    }
    // mounted() {
    //   markList(this.currentBook).then(response => {
    //     if (response && response.status === 200) {
    //       const data = response.data
    //       console.log(data)
    //     }
    //   })
    // }
  }
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
  @import "../../assets/styles/global";
  .ebook-bookmark {
    position: absolute;
    top: px2rem(-85);// -35
    left: 0;
    z-index: 200;
    width: 100%;
    height: px2rem(85);// 35
    .ebook-bookmark-text-wrapper {
      position: absolute;
      right: px2rem(105);// 45
      bottom: 0;
      display: flex;
      .ebook-bookmark-down-wrapper {
        font-size: px2rem(14);
        color: white;
        transition: all .2s linear;
        @include center;
      }
      .ebook-bookmark-text {
        font-size: px2rem(14);
        color: white;
      }
    }
    .ebook-bookmark-icon-wrapper {
      position: absolute;
      right: 0;
      bottom: 0;
      margin-right: px2rem(32); //15
    }
  }
</style>
